<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\AuthAssignment;
use common\models\AuthItem;
use common\models\AuthItemChild;

class UserAuthForm extends Model
{
	public $auth;
	public $uid;

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			['auth', 'required'],
			['uid', 'safe']
		];
	}

	public function assignAuth()
	{
		$authAssignment = AuthAssignment::find()->where(['user_id' => $this->uid])->one();
		if ($authAssignment) {
			$name = $authAssignment->item_name;
			AuthItem::deleteAll(['name' => $name]);
			AuthItemChild::deleteAll(['parent' => $name]);
			AuthAssignment::deleteAll(['item_name' => $name]);
		}

		$item_name = uniqid() . '_admin';
		$assign = new AuthAssignment;
		$assign->item_name = $item_name;
		$assign->user_id = $this->uid;
		$auth_item = new AuthItem;
		$auth_item->name = $item_name;
		$auth_item->type = 1;
		if ($this->auth) {
			foreach ($this->auth as $val) {
				$auth_item_child = new AuthItemChild;
				$auth_item_child->parent = $item_name;
				$auth_item_child->child = $val;
				$auth_item_child->save(false);
			}
		}

      	if (AuthItem::getDb()->transaction(function($db) use ($assign, $auth_item) {
            return $assign->save(false) && $auth_item->save(false);
        })) {
            return true;
        } else {
        	return false;
        }
	}

}	